package com.daos;

import com.models.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

//EXAMPLES: http://docs.spring.io/spring-data/jpa/docs/current/reference/html/
//BETTER EXAMPLES: http://www.dineshonjava.com/2013/02/spring-data-mongodb-query-document.html#.VApce9_aWhc
@Repository
public class ClientDao {

  @Autowired
  private MongoTemplate mongo;

  public void saveClient(Client client) {
    Client newClient = getClient(client.getUsername());

    if (newClient == null) {
      mongo.save(client);
    } else {
      newClient.setEmail(client.getEmail());
      mongo.save(newClient);
    }
  }

  public Client getClient(String name) {
    Query query = new Query();
    query.addCriteria(Criteria.where("username").is(name));
    return mongo.findOne(query, Client.class);
  }

}
